import { _decorator, Component, error, JsonAsset, Label, Node, ProgressBar } from 'cc';
import { UIBase } from '../UIFramework/UIBase';
import { ResMgr } from '../Res/ResMgr';
import { BundleConfig } from './BundleConfig';
import { DataBaseMgr } from '../Data/DataBaseMgr';
import { DataMgr } from '../Data/DataMgr';
const { ccclass, property } = _decorator;

@ccclass('UILoading')
export class UILoading extends UIBase {
    @property({visible:true,displayName:'第一个UI'})
    private _firstUIName:string = ''
    //加载数量
    private _loadingCount:number = 0;
    //资源总数
    private _totalCount:number = 0;
    private _loadingBar:ProgressBar = null;
    private _lbLoading:Label = null;
    onInit(...rest: any[]): void {
        this._loadingBar = this.getComp<ProgressBar>('_LoadingBar','ProgressBar');
        this._lbLoading = this.getComp<Label>('_LbLoading','Label')
        this._caculateLoadingCount();
        this._loadRes();
    }

    //计算需要加载的资源总数，以后可以处理，按需排除掉，以减少游戏启动时间，加载一些必备资源。目前是配置文件里所有
    private _caculateLoadingCount(){
        for(let key in BundleConfig){
            if(key =='UIFramework'){
                continue;
            }
            let urls =BundleConfig[key].urls;
            for(let url of urls){
                this._totalCount++;
            }
        }
    }

    private async _loadRes(){
        for(let key in BundleConfig){
            if(key =='UIFramework'){
                continue;
            }
            let urls =BundleConfig[key].urls;
            for(let url of urls){
                await ResMgr.instance.loadRes(BundleConfig[key].name,url).then(ret=>{
                    //单个资源加载完成。处理资源加载完后的逻辑
                    if(ret instanceof JsonAsset){
                        //加载后的资源是json那么创建出具体数据管理者去添加到数据管理者
                        let mgr = new DataBaseMgr();
                        mgr.addData(ret);
                        DataMgr.instance.addMgr(ret.name+'Mgr',mgr);
                    }
                });
                this._loadingCount++;
                let progress =this._loadingCount/this._totalCount;
                this._loadingBar.progress = progress;
                this._lbLoading.string = '正在加载...'+(progress*100).toFixed(2)+'%';
                if(progress>=1){
                    this.openUI(this._firstUIName,true,true,null);
                    return;
                }
            }   
            
        }
    }
}


